package com.example.tipapp

import android.icu.text.DecimalFormat
import android.icu.text.DecimalFormatSymbols
import android.icu.text.NumberFormat
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.tipapp.ui.theme.TipAppTheme
import java.util.Locale

//测试是否同步到远程
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TipAppTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Surface(modifier = Modifier.padding(innerPadding) ) {
                        TipTimeLayout()
                    }
                }
            }
        }
    }
}

// DecimalVisualTransformation 整数千分位显示（如 4521763.5 显示为 4,521,763.5），
// 但实际存储值仍为 "3.5"，避免干扰计算。
class DecimalVisualTransformation : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        val original = text.text
        if (original.isEmpty()) return TransformedText(AnnotatedString(""), OffsetMapping.Identity)

        return try {
            // 0. 预处理：移除原始输入中的逗号
            val sanitized = original.replace(",", "")
            val hasDecimal = original.contains('.')
            val parts = sanitized.split('.')

            // 分割整数和小数部分
            val integerPart = when {
                original == "." -> "0"
                parts.first().isEmpty() -> "0"
                else -> parts.first()
            }
            val decimalPart = parts.getOrNull(1)?.take(2) ?: ""  //限制最多两位小数

            val formatter = DecimalFormat("#,###").apply {
                decimalFormatSymbols = DecimalFormatSymbols(Locale.US).apply {
                    groupingSeparator = ','
                }
            }
            val formattedInteger = try {
                // 特殊处理，“0”显示，但避免格式化
                if (integerPart == "0") "0"
                else formatter.format(integerPart.toBigInteger())
            } catch (e: Exception) {
                integerPart  // 回退原始整数
            }

            // 构建完整字符串
            val formattedText = buildString {
                append(formattedInteger)
                if (hasDecimal) {
                    append(".")
                    append(decimalPart)  // 直接使用用户输入的小数部分
                }
            }

            // 精确的光标偏移映射
            val offsetMapping = object : OffsetMapping{
                override fun originalToTransformed(offset: Int): Int {
                    if (offset == 0) return 0

                    // 计算原始文本前缀
                    val rawPrefix = original.substring(0, offset.coerceAtMost(original.length))
                    val sanitizedPrefix = rawPrefix.replace(",", "")
                    val hasDecimalInPrefix = rawPrefix.contains('.')  // 使用前缀而非整个字符串

                    // 分割当前前辍
                    val prefixParts = sanitizedPrefix.split('.')
                    val intSeg = prefixParts.first()
                    val decimalSeg = prefixParts.getOrNull(1) ?: ""

                    // 输入“.”闪退，关键修复1：空整数部分处理
                    val intLen = when {
                        intSeg.isEmpty() && hasDecimalInPrefix -> 1 // 显示“0”的长度
                        intSeg.isEmpty() -> 0
                        else -> try {
                            formatter.format(intSeg.toBigInteger()).length
                        } catch (e: Exception) {
                            intSeg.length
                        }
                    }
                    // 关键修复2：小数部分长度(不超过实际输入）
                    val decimalLen = minOf(
                        decimalSeg.length,
                        if (hasDecimalInPrefix) 2 else 0  // 无小数点时，不计算小数长度
                    )

                    return intLen + (if (hasDecimalInPrefix) 1 + decimalLen else 0)
                }

                override fun transformedToOriginal(offset: Int): Int {
                    if (offset == 0) return 0
                    // 计算有效字符位置（忽略逗号）
                    val prefix = formattedText.substring(0, offset)
                    val noComma = prefix.replace(",", "")

                    // 确保返回的位置不超过原始文本的长度
                    return  noComma.length.coerceAtMost(original.length)
                }
            }
            TransformedText(AnnotatedString(formattedText), offsetMapping)
        } catch (e: Exception) {
            TransformedText(AnnotatedString(original), OffsetMapping.Identity) // 异常回退
        }
    }
}

private fun calculateTip(
    amount: Double,
    tipPercent: Double = 15.0,
    roundUp: Boolean): String
{
    var tip = tipPercent / 100 * amount
    if (roundUp)
        tip = kotlin.math.ceil(tip)
    return NumberFormat.getCurrencyInstance().format(tip)
}

//测试参。。
@Composable
fun TipTimeLayout() {
    var amountInput by remember { mutableStateOf("") }
    var lastValidText by remember { mutableStateOf("") }
    var tipInput by remember { mutableStateOf("") }
    var roundUp by remember { mutableStateOf(false) }

    val focusManager = LocalFocusManager.current
    val tipPercent = tipInput.toDoubleOrNull() ?: 0.0
    val amount = amountInput.toDoubleOrNull() ?: 0.0
    val tip = calculateTip(amount, tipPercent, roundUp)

    Column(
        modifier = Modifier
            .statusBarsPadding()
            .padding(horizontal = 40.dp)
            .verticalScroll(rememberScrollState())
            .safeDrawingPadding(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = stringResource(R.string.TipAppName),
            fontSize = 24.sp,
            modifier = Modifier
                .padding(bottom = 16.dp, top = 40.dp)
                .align(alignment = Alignment.Start)
        )
        EditNumberField(
            label = R.string.bill_amount,
            leadingIcon = R.drawable.money,
            keyboardOptions = KeyboardOptions.Default.copy(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Next
            ),
            keyboardActions = KeyboardActions(
                onNext = { focusManager.moveFocus(FocusDirection.Down) }
            ),
            value = amountInput,
            onValueChange = { newInput ->
                // 只允许数字和小数点：通过 filter { it.isDigit() || it == '.' } 实现。
                val filtered = newInput.filter { it.isDigit() || it == '.' }
                val parts = filtered.split('.')
                // 增强验证逻辑
                val isValid = when {
                    // 最多一个小数点：用 split('.') 检测分段数量（超过2段即非法）。
                    parts.size > 2 -> false
                    // 小数位 ≤ 2：检测小数点后字符串长度（parts[1].length > 2 则拒绝）。
                    parts.size == 2 && parts[1].length > 2 -> false
                    // 明确允许首位小数点输入
                    filtered == "." -> true
                    else -> true
                }

                if (isValid) {
                    amountInput = filtered
                    lastValidText = filtered  // 更新合法值
                } else {
                    //非法输入时恢复湖区我合法值
                    amountInput = lastValidText
                }
            },
            modifier = Modifier
                .padding(bottom = 32.dp)
                .fillMaxWidth()
        )

        EditNumberField(
            label = R.string.how_was_the_service,
            leadingIcon = R.drawable.percent,
            keyboardOptions = KeyboardOptions.Default.copy(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done

            ),

            keyboardActions = KeyboardActions(
                onDone = { focusManager.clearFocus() }
            ),
            value = tipInput,
            onValueChange = { tipInput = it },
            modifier = Modifier
                .padding(bottom = 32.dp)
                .fillMaxWidth()
        )
        RoundTheTipRow(
            roundUp = roundUp,
            onRoundUpChanged = { roundUp = it },
            modifier = Modifier.padding(bottom = 32.dp)
        )
        Spacer(Modifier.height(24.dp))
        Text(
            text = stringResource(R.string.TipCost, tip),
            style = MaterialTheme.typography.displaySmall,
            modifier = Modifier
                .align(alignment = Alignment.Start)
        )
        Spacer(modifier = Modifier.height(150.dp))
    }
}

@Composable
fun EditNumberField(
    @StringRes label: Int,
    @DrawableRes leadingIcon: Int,
    keyboardOptions: KeyboardOptions,
    keyboardActions: KeyboardActions,
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    TextField(
        value = value,
        onValueChange = onValueChange,
        singleLine = true,
        leadingIcon = { Icon(painter = painterResource(id = leadingIcon), null) },
        label = { Text(stringResource(label)) },
        // 弹出数字键盘
        keyboardOptions = keyboardOptions,
        keyboardActions = keyboardActions,
        visualTransformation = DecimalVisualTransformation(), //可选：格式化显示
        modifier = modifier
    )
}

@Composable
fun RoundTheTipRow(
    roundUp: Boolean,
    onRoundUpChanged: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .size(48.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = stringResource(R.string.round_up_tip))
        Switch(
            checked = roundUp,
            onCheckedChange = onRoundUpChanged,
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentWidth(Alignment.End)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun TipTimeLayoutPreview() {
    TipAppTheme {
        TipTimeLayout()
    }
}